/*
 * Copyright (c) 2011 Shanda Corporation. All rights reserved.
 *
 * Created on 2011-8-9.
 */
package com.whq.knowverywell.business.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.whq.knowverywell.business.db.helper.MainSQLiteOpenHelper;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.StringUtil;

/**
 * 封装对SQLit表: tbl_conf 的操作.
 *
 * @author wanghuaiqiang
 */
public class TblConfHandler extends AbstractTblConfHandler {
    private static final String TAG = "TblConfHandler";
    private MainSQLiteOpenHelper mainSQLiteOpenHelper = null;
    
    public static final String TBL_CONF = "tbl_conf";
    
    private static final String COLUMN_KEY = "conf_key";
    private static final String COLUMN_VAL = "conf_val";
    
    public static final String CREATE_TABLE_SQL = 
    		" CREATE TABLE " + TBL_CONF + " (" + COLUMN_KEY + " TEXT PRIMARY KEY, " + COLUMN_VAL + " TEXT);";
    
    public static final String KEY_LOGIN_GROUP_CODE = "key_login_group_code";
    public static final String KEY_LOGIN_USER_NAME 	= "key_login_user_name";
    public static final String KEY_LOGIN_TOKEN      = "key_login_token";
    
    
    public TblConfHandler(Context context) {
        mainSQLiteOpenHelper = new MainSQLiteOpenHelper(context);
    }
    
    public void saveOneConf(String key, String val) {
    	this.initCache();
    	LogUtil.i(TAG, "保存配置信息: " + key + " = " + val);
        
        if (StringUtil.isBlank(key)) {
        	return ;
        }
        
        SQLiteDatabase m_oData = null;
        Cursor oCursor = null;
        try {
            m_oData = this.mainSQLiteOpenHelper.getWritableDatabase();
            
            String sql = "SELECT * FROM " + TBL_CONF + " WHERE " + COLUMN_KEY + "=? ";
            oCursor = m_oData.rawQuery(sql, new String[]{key});
            if (oCursor.moveToFirst()) {
            	sql = "update " + TBL_CONF + " set " + COLUMN_VAL + "=? where " + COLUMN_KEY + "=? ";
            	Object[] paramsValue = new Object[]{val, key};
                m_oData.execSQL(sql, paramsValue);
            } else {
            	sql = "INSERT INTO " + TBL_CONF + " (" + COLUMN_KEY + ", " + COLUMN_VAL + ") VALUES(?, ?)";
            	Object[] paramsValue = new Object[]{key, val};
                m_oData.execSQL(sql, paramsValue);
            }
            this.saveToCache(key, val);
            LogUtil.i(TAG, "sql：" + sql);
            LogUtil.i(TAG, "保存配置信息: " + key + " = " + val + " 成功");
        } catch (Exception e) {
            LogUtil.e(TAG, "保存配置信息发生异常：", e);
        } finally {
            if (oCursor != null) {
                oCursor.close();
                oCursor = null;
            }
            if (m_oData != null) {
                m_oData.close();
                m_oData = null;
            }
        }
    }
    
    public void delAllRecords() {
        LogUtil.i(TAG, "删除所有配置信息");
        SQLiteDatabase m_oData = null;
        try {
        	m_oData = this.mainSQLiteOpenHelper.getWritableDatabase();
            String sql  = "DELETE FROM " + TBL_CONF;
            m_oData.execSQL(sql);
            LogUtil.i(TAG, "sql：" + sql);
            
            this.clearCache();
            LogUtil.i(TAG, "删除所有配置信息 成功");
        } catch (Exception e) {
            LogUtil.e(TAG, "删除所有配置信息发生异常：", e);
        } finally {
            if (m_oData != null) {
                m_oData.close();
                m_oData = null;
            }
        }
    }
    
    public void saveOneConf(String key, Object val) {
    	saveOneConf(key, String.valueOf(val));
    }
    
    public String getOneConf(String key) {
    	this.initCache();
        LogUtil.i(TAG, "获取配置信息[key=" + key + "]");
        String ret = this.getFromCache(key);
        if (ret == null) {
        	ret = "";
        }
        return ret;
    }
    
    public int getOneIntConf(String key, int defaultVal) {
    	String tmp = this.getOneConf(key);
    	if (StringUtil.isBlank(tmp)) {
    		return defaultVal;
    	}
    	try {
    		return Integer.valueOf(tmp);
    	} catch (Exception e) {
    		LogUtil.e(TAG, "将[" + tmp + "]转换成int出错：", e);
    	}
    	return defaultVal;
    }
    
    public long getOneLongConf(String key, long defaultVal) {
    	String tmp = this.getOneConf(key);
    	if (StringUtil.isBlank(tmp)) {
    		return defaultVal;
    	}
    	try {
    		return Long.valueOf(tmp);
    	} catch (Exception e) {
    		LogUtil.e(TAG, "将[" + tmp + "]转换成long出错：", e);
    	}
    	return defaultVal;
    }
    
    public double getOneDoubleConf(String key, double defaultVal) {
    	String tmp = this.getOneConf(key);
    	if (StringUtil.isBlank(tmp)) {
    		return defaultVal;
    	}
    	try {
    		return Double.valueOf(tmp);
    	} catch (Exception e) {
    		LogUtil.e(TAG, "将[" + tmp + "]转换成double出错：", e);
    	}
    	return defaultVal;
    }
    
    public void removeOneConf(String key) {
    	this.initCache();
        LogUtil.i(TAG, "删除配置信息[key=" + key + "]");
        SQLiteDatabase m_oData = null;
        try {
            m_oData = this.mainSQLiteOpenHelper.getWritableDatabase();
            String sql  = "DELETE FROM " + TBL_CONF + " WHERE " + COLUMN_KEY + "=? ";
            m_oData.execSQL(sql, new String[]{key});
            
            this.removeFromCache(key);
            LogUtil.i(TAG, "sql：" + sql);
            LogUtil.i(TAG, "删除配置信息[key=" + key + "] 成功");
        } catch (Exception e) {
            LogUtil.e(TAG, "删除配置信息[key=" + key + "]发生异常：", e);
        } finally {
            if (m_oData != null) {
                m_oData.close();
                m_oData = null;
            }
        }
    }
    
	@Override
	protected void allRecordsFromDbToCache() {
		LogUtil.i(TAG, "获取所有的配置信息");
        SQLiteDatabase m_oData = null;
        Cursor oCursor = null;
        try {
            m_oData = this.mainSQLiteOpenHelper.getReadableDatabase();
            String sql = "SELECT * FROM " + TBL_CONF ;
            oCursor = m_oData.rawQuery(sql, new String[]{});
            while (oCursor.moveToNext()) {
            	try {
            		String key = oCursor.getString(oCursor.getColumnIndex(COLUMN_KEY));
                	String value = oCursor.getString(oCursor.getColumnIndex(COLUMN_VAL));
                	saveToCache(key, value);
            	} catch (Exception ex) {
            		
            	}
            }
            LogUtil.i(TAG, "sql：" + sql);
            LogUtil.i(TAG, "获取配置信息成功");
        } catch (Exception e) {
            LogUtil.e(TAG, "获取配置信息发生异常：", e);
        } finally {
            if (oCursor != null) {
                oCursor.close();
                oCursor = null;
            }
            if (m_oData != null) {
                m_oData.close();
                m_oData = null;
            }
        }
	}
}